/**
 * 详情对话框
 */


layui.use(['form', 'admin', 'ax', 'jquery', 'steps', 'laydate', 'formSelects'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var formSelects = layui.formSelects;
    var resultData;

    var productList = [];
    var selectProducts = [];
    var selectWorker;
    var selectClient;
    var selectFarmId;

    //让当前iframe弹层高度适应
    admin.iframeAuto();
    //渲染时间选择框
    // laydate.render({
    //     elem: '#releaseStartTime'
    // });


    //获取详情信息，填充表单
    if (!Feng.isUndefined(Feng.getUrlParam("saleId"))) {
        var ajax = new $ax(Feng.ctxPath + "/api/sale/detail?saleId=" + Feng.getUrlParam("saleId"));
        var result = ajax.start();
        form.val('saleForm', result.data);
        resultData = result.data;

        selectWorker = resultData.worker;
        selectClient = resultData.client;
        selectFarmId = resultData.farmId;
        if (!Feng.isUndefined(resultData.productList)) {
            //产品验收就改
            selectProducts = JSON.parse(resultData.productList);
        }
    }


    loadResultData();

    //加载信息
    function loadResultData() {


        // UI控制
        loadUIControl();

        // 产品
        loadProductList();

        // 人员
        loadWorkerList();

        //客户
        loadClientList();

        //养殖池
        loadFarmList();


    }

    function loadUIControl() {

        if (!Feng.isUndefined(Feng.getUrlParam("saleId"))) {
            $("#basicForm").addClass("layui-not-events");
            $("#productForm").addClass("layui-not-events");
            $("#productItemList").addClass("layui-not-events");
            $("#workerForm").addClass("layui-not-events");
            $("#comfireButton").addClass("layui-not-events");
            $("#payWayForm").addClass("layui-not-events");

        }
    }

    //加载目标产品

    function loadProductList() {

        $("#productSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/api/product/list", function (data) {

            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].title;
                var value = data.data[i].productId;
                var price = data.data[i].price;
                var dict = {"value": value, "name": name, "price": price, "number": "0", "total": "0"};
                productList.push(dict);
            }
            mutilProducts();
            form.render();

        }, function (data) {
        });
        ajax.start();
    }


    function mutilProducts() {
        if (Feng.isArray(productList)) {

            formSelects.data('productSelect', 'local', {
                arr: productList
            });
            if (Feng.isArray(selectProducts)) {
                var productIds = [];
                for (var i = 0; i < selectProducts.length; i++) {
                    var select = selectProducts[i];
                    productIds.push(select.value);
                }
                formSelects.value('productSelect', productIds);
                loadProductItemList();
                loadTotalPirce();

            }
        }

    }

    formSelects.on('productSelect', function (id, vals, val, isAdd, isDisabled) {
        // alert("选择了: " + val.name);
        selectProducts = vals;
        loadProductItemList();

    }, true);


    function loadProductItemList() {
        $("#productItemList").html('');
        for (var i = 0; i < selectProducts.length; i++) {
            var value = selectProducts[i].value;
            var name = selectProducts[i].name;
            var price = selectProducts[i].price;
            var number = selectProducts[i].number;
            var total = number * price;

            var numberName = 'product_number_' + i;
            var totalName = 'product_total_' + i;

            var valueForm = '<div class="layui-inline layui-col-md3">' +
                '<label class="layui-form-label">产品编码</label>' +
                '<div class="layui-input-block" style="line-height: 38px">' +
                value +
                '</div>' +
                '</div>';

            var nameForm = '<div class="layui-inline layui-col-md2">' +
                '<label class="layui-form-label">产品</label>' +
                '<div class="layui-input-block" style="line-height: 38px">' +
                name +
                '</div>' +
                '</div>';

            var priceForm = '<div class="layui-inline layui-col-md2">' +
                '<label class="layui-form-label">单价(元)</label>' +
                '<div class="layui-input-block" style="line-height: 38px">' +
                price +
                '</div>' +
                '</div>';


            var numberForm = '<div class="layui-inline layui-col-md2"><label class="layui-form-label">数量</label>' +
                '<div class="layui-input-block">' +
                '<input id= ' + numberName + ' name=' + numberName + ' value=' + number + '  type="number"  class="layui-input"/>' +
                '</div>' +
                '</div>';

            var totalForm = '<div class="layui-inline layui-col-md2"><label class="layui-form-label">总价(元)</label>' +
                '<div class="layui-input-block">' +
                '<input id= ' + totalName + ' name=' + totalName + ' value=' + total + '  type="number"  class="layui-input" disabled/>' +
                '</div>' +
                '</div>';

            $("#productItemList").append(valueForm);
            $("#productItemList").append(nameForm);
            $("#productItemList").append(priceForm);
            $("#productItemList").append(numberForm);
            $("#productItemList").append(totalForm);



            loadKeyupPirce(numberName,totalName,price);
        }

    }

    function loadKeyupPirce(numberName,totalName,price) {
        //联动时间
        var numberId = "#" + numberName;
        var totalId = "#" + totalName;
        $(numberId).keyup(function (e) {
            var origin = $(numberId).val();
            $(totalId).val(origin * price);

            loadTotalPirce();
        });
    }

    function loadTotalPirce() {

        var totalPirce = 0;
        for (var i = 0; i < selectProducts.length; i++) {
            var totalClass = "product_total_" + i;
            var total = $("#" + totalClass).val();
            if (!Feng.isUndefined(total)) {
                totalPirce += parseFloat(total);
            }
        }
        $("#totalPrice").val(totalPirce + '');
    }

    //=========== 加载工作人员 ========== //

    function loadWorkerList() {

        $("#workerSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/mgr/allList", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].name;
                var account = data.data[i].account;
                var value = account + "-" + name;

                var select = '';
                if (value === selectWorker) {
                    select = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectWorker) && value !== selectWorker) {
                    selectWorker = value;
                    select = 'selected';
                }
                var selected = select;
                $("#workerSelect").append('<option value="' + value + '"   ' + selected + '>' + value + '</option>');
            }
            form.render();

        }, function (data) {
        });
        ajax.start();
    }

    form.on('select(workerSelect)', function (data) {
        selectWorker = data.value;
    });

    //=========== 加载客户人员 ========== //
    function loadClientList() {

        $("#clientSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/api/client/list", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var clientId = data.data[i].clientId;
                var name = data.data[i].name;
                var phone = data.data[i].phone;
                var chargeName = data.data[i].chargeName;
                var businessName = data.data[i].businessName;
                var address = data.data[i].address;
                var value = "姓名: " + name + " 负责人: " + chargeName + " 业务员: " + businessName;
                var select = '';
                if (clientId === selectClient) {
                    select = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectClient) && value !== selectClient) {
                    selectClient = value;
                    select = 'selected';
                }
                var selected = select;
                $("#clientSelect").append('<option value="' + clientId + '"  ' + selected + '>' + value + '</option>');
            }
            form.render();

        }, function (data) {
        });
        ajax.start();
    }

    form.on('select(clientSelect)', function (data) {
        selectClient = data.value;
    });

    //加载养殖场

    function loadFarmList() {

        $("#farmSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/api/farm/list", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].title;
                var value = data.data[i].farmId;
                var selected = '';
                if (value === selectFarmId) {
                    selected = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectFarmId) && value !== selectFarmId) {
                    selectFarmId = value;
                    selected = 'selected';
                }
                // name = value + '-' + name;
                $("#farmSelect").append('<option value="' + value + '"  ' + selected + '>' + name + '</option>');

            }
            form.render();

        });
        ajax.start();
    }

    form.on('select(farmSelect)', function (data) {
        selectFarmId = data.value;

    });

    //表单提交事件

    function reloadProductList() {
        for (var i = 0; i < selectProducts.length; i++) {
            var product = selectProducts[i];
            var numberClass = "product_number_" + i;
            var number = $("#" + numberClass).val();
            if (!Feng.isUndefined(number)) {
                product.number = number;
            }

            var totalClass = "product_total_" + i;
            var total = $("#" + totalClass).val();
            if (!Feng.isUndefined(total)) {
                product.total = total;
            }

            selectProducts[i] = product;

        }
    }

    function buildRequest() {

        //构造请求体
        reloadProductList();


        if ($("#title").val() === '') {
            Feng.error("销售代号不能为空");
            return false;
        }
        if (Feng.isUndefined(selectWorker)) {
            Feng.error("销售人员都不能为空");
            return false;
        }

        if (Feng.isUndefined(selectClient)) {
            Feng.error("客户都不能为空");
            return false;
        }

        if (Feng.isArray(selectProducts) === false) {
            Feng.error("产品不能为空");
            return false;
        }

        if (Feng.isArray(selectFarmId) === false) {
            Feng.error("养殖场不能为空");
            return false;
        }

        return true;
    }

    form.on('submit(btnSubmit)', function (data) {

        var result = buildRequest();
        if (result === false) {
            return;
        }
        data.field.worker = selectWorker;
        data.field.client = selectClient;
        data.field.farmId = selectFarmId;
        data.field.productList = JSON.stringify(selectProducts);

        var url = "/api/sale/addItem";
        var add = true;
        if ($.trim(data.field.saleId) !== '') {
            url = "/api/sale/editItem";
            add = false;
        }

        var ajax = new $ax(Feng.ctxPath + url, function (data) {
            if (add === true) {
                Feng.success("新增成功！");
                window.location.href = Feng.ctxPath + '/api/sale'
            } else {
                Feng.success("更新成功！");
                window.location.reload();
            }
        }, function (data) {
            Feng.error("请求失败！" + data.responseJSON.message)
        });
        ajax.set(data.field);
        ajax.start();

        return false;
    });
    //返回按钮
    $("#backupPage").click(function () {
        window.location.href = Feng.ctxPath + '/api/sale'
    });

});